<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<title>dom节点转成json数据</title>
</head>
<body>

<div id="jsContainer">
	<ul class="js-test" id="jsParent">
	    <li data-index="0">1</li>
	    <li data-index="1">2</li>
	</ul>
	<span style="font-weight: bold;">3</span>
	4
</div>
<script>
function dom2json() {
	const jsContainer = document.querySelector("#jsContainer")

	function texthandle(str) {
		return str.replace(/\s/g, '')
	}

	function getTagName(dom) {
		return dom.nodeName.toLocaleLowerCase();
	}

	function getTagAttrs(dom) {
		var attr = Array.from(dom.attributes)
		var obj = {}
		attr.forEach(atr => obj[atr.name] = atr.value)
		return attr.length ? obj : null;
	}

	function domJson(dom) {
        var obj = {
            tag: getTagName(dom)
        }
        if (dom.nodeType == 1) {//元素节点
            var attrs = getTagAttrs(dom);
            if (attrs) obj.attributes = attrs;
            obj.children = Array.from(dom.childNodes).filter(child => {
                return !(child.nodeType == 3 && !child.textContent.trim());//把文本节点且内容为空的过滤掉
            }).map(child => domJson(child))
            return obj;
        }
        if (dom.nodeType == 3) {//文本节点
            obj.content = texthandle(dom.textContent)
            return obj
        }
    }

	return domJson(jsContainer);
}
console.log(dom2json(document.querySelector('#jsContainer')));
</script>
</body>
</html>